import React, { useEffect, useState } from "react";
import { Table, Button, Modal, Form, Input, Switch, message, Space, Popconfirm } from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";

// 模拟 API 服务
const mockRoleService = {
  // 模拟数据存储
  roles: [
    { id: 1, name: "管理员", description: "系统管理员，拥有所有权限", status: true },
    { id: 2, name: "编辑者", description: "内容编辑人员", status: true },
    { id: 3, name: "查看者", description: "只读用户", status: false }
  ],

  // 模拟获取角色列表
  getRoles: () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟 80% 成功率
        if (Math.random() > 0.2) {
          resolve([...mockRoleService.roles]); // 返回副本
        } else {
          reject(new Error("网络错误"));
        }
      }, 500); // 模拟网络延迟
    });
  },

  // 模拟添加角色
  addRole: (role) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (Math.random() > 0.1) { // 90% 成功率
          const newRole = {
            id: Math.max(0, ...mockRoleService.roles.map(r => r.id)) + 1,
            ...role,
            status: role.status !== undefined ? role.status : true
          };
          mockRoleService.roles.push(newRole);
          resolve(newRole);
        } else {
          reject(new Error("添加失败"));
        }
      }, 300);
    });
  },

  // 模拟更新角色
  updateRole: (id, updates) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (Math.random() > 0.1) { // 90% 成功率
          const index = mockRoleService.roles.findIndex(role => role.id === id);
          if (index !== -1) {
            mockRoleService.roles[index] = { ...mockRoleService.roles[index], ...updates };
            resolve(mockRoleService.roles[index]);
          } else {
            reject(new Error("角色不存在"));
          }
        } else {
          reject(new Error("更新失败"));
        }
      }, 300);
    });
  },

  // 模拟删除角色
  deleteRole: (id) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (Math.random() > 0.1) { // 90% 成功率
          const index = mockRoleService.roles.findIndex(role => role.id === id);
          if (index !== -1) {
            mockRoleService.roles.splice(index, 1);
            resolve({ success: true });
          } else {
            reject(new Error("角色不存在"));
          }
        } else {
          reject(new Error("删除失败"));
        }
      }, 300);
    });
  },

  // 模拟更新角色状态
  updateRoleStatus: (id, status) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (Math.random() > 0.1) { // 90% 成功率
          const index = mockRoleService.roles.findIndex(role => role.id === id);
          if (index !== -1) {
            mockRoleService.roles[index].status = status;
            resolve({ success: true });
          } else {
            reject(new Error("角色不存在"));
          }
        } else {
          reject(new Error("状态更新失败"));
        }
      }, 200);
    });
  }
};

const Role = () => {
  const [roles, setRoles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState(null);
  const [form] = Form.useForm();

  // 获取角色数据
  const fetchRoles = async () => {
    setLoading(true);
    try {
      const data = await mockRoleService.getRoles();
      setRoles(data);
    } catch (error) {
      message.error("获取角色列表失败: " + error.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRoles();
  }, []);

  // 处理添加/编辑角色
  const handleFinish = async (values) => {
    try {
      if (editingRole) {
        // 编辑角色
        await mockRoleService.updateRole(editingRole.id, values);
        message.success("角色更新成功");
      } else {
        // 添加角色
        await mockRoleService.addRole(values);
        message.success("角色添加成功");
      }
      setModalVisible(false);
      form.resetFields();
      setEditingRole(null);
      fetchRoles(); // 重新获取数据
    } catch (error) {
      message.error(editingRole ? "角色更新失败: " + error.message : "角色添加失败: " + error.message);
    }
  };

  // 处理编辑角色
  const handleEdit = (record) => {
    setEditingRole(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  // 处理删除角色
  const handleDelete = async (id) => {
    try {
      await mockRoleService.deleteRole(id);
      message.success("角色删除成功");
      fetchRoles(); // 重新获取数据
    } catch (error) {
      message.error("角色删除失败: " + error.message);
    }
  };

  // 处理启用/禁用角色
  const handleStatusChange = async (checked, record) => {
    try {
      await mockRoleService.updateRoleStatus(record.id, checked);
      message.success(`角色${checked ? '启用' : '禁用'}成功`);
      fetchRoles(); // 重新获取数据
    } catch (error) {
      message.error(`角色${checked ? '启用' : '禁用'}失败: ` + error.message);
    }
  };

  const columns = [
    {
      title: "角色名称",
      dataIndex: "name",
      key: "name"
    },
    {
      title: "角色描述",
      dataIndex: "description",
      key: "description"
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (text, record) => (
        <Switch
          checked={text}
          onChange={(checked) => handleStatusChange(checked, record)}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      )
    },
    {
      title: "操作",
      key: "action",
      render: (text, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            size="small"
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除此角色吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setEditingRole(null);
            form.resetFields();
            setModalVisible(true);
          }}
        >
          新增角色
        </Button>
      </div>

      <Table
        dataSource={roles}
        columns={columns}
        loading={loading}
        rowKey="id"
        pagination={{
          pageSize: 10
        }}
      />

      <Modal
        title={editingRole ? "编辑角色" : "新增角色"}
        visible={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
          setEditingRole(null);
        }}
        onOk={() => form.submit()}
      >
        <Form
          form={form}
          onFinish={handleFinish}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: "请输入角色名称" }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="角色描述"
          >
            <Input.TextArea placeholder="请输入角色描述" rows={3} />
          </Form.Item>
          {editingRole && (
            <Form.Item
              name="status"
              label="状态"
              valuePropName="checked"
            >
              <Switch checkedChildren="启用" unCheckedChildren="禁用" />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default Role;